package com.heima.article.stream;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.mess.UpdateArticleMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
@Slf4j
public class HotArticleStreamHandler {

    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder){
        KStream<String, String> stream = streamsBuilder.stream(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC);

        stream.map((key, value) -> {
            log.info("key: " + key + " value: " + value);
            UpdateArticleMess mess = JSON.parseObject(value, UpdateArticleMess.class);
            return new KeyValue<>(mess.getArticleId().toString(), mess.getType() + ":" + mess.getAdd());
        })
                .groupBy((key, value) -> key)
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
//                .  自定义聚合函数
                .aggregate(new Initializer<String>() {

                    /**
                     * Initializer: 代表的是初始化方法-主要的的作用就是每次时间创建开始的适合对统计的结果进行初始化和归0
                     * 这个方法每个时间窗框只会执行一次
                     *
                     * @return the initial value for an aggregation
                     */
                    @Override
                    public String apply() {
                        return "COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0";
                    }
                }, new Aggregator<String, String, String>() {
                    /**
                     * 每次消息来的时候都会执行统计
                     * @param key 当前消息的key 文章的id
                     * @param value 当前消息的value值 like:1
                     * @param aggregate 上一次统计的结果如果的第一个消息则是初始化的结果
                     * @return
                     */
                    @Override
                    public String apply(String key, String value, String aggregate) {
                        if(StringUtils.isEmpty(value)){
                            return aggregate;
                        }

                        //还原上一次统计的结果到变量中
                        String[] arggregates = aggregate.split(",");//[COLLECTION:0,COMMENT:0]
                        int col = 0,com=0,lik=0,vie=0;

                        for (String arggregate : arggregates) { // arggregate=COLLECTION:0
                            String[] strs = arggregate.split(":"); // [COLLECTION,0]
                            switch (UpdateArticleMess.UpdateArticleType.valueOf(strs[0])){
                                case COLLECTION:
                                    col = Integer.parseInt(strs[1]);
                                    break;
                                case COMMENT:
                                    com = Integer.parseInt(strs[1]);
                                    break;
                                case LIKES:
                                    lik = Integer.parseInt(strs[1]);
                                    break;
                                case VIEWS:
                                    vie = Integer.parseInt(strs[1]);
                            }
                        }

                        //累加当前消息的结果
                        String[] strs = value.split(":");// [view, -1]
                        switch (UpdateArticleMess.UpdateArticleType.valueOf(strs[0])){
                            case COLLECTION:
                                col += Integer.parseInt(strs[1]);
                                break;
                            case COMMENT:
                                com += Integer.parseInt(strs[1]);
                                break;
                            case LIKES:
                                lik += Integer.parseInt(strs[1]);
                                break;
                            case VIEWS:
                                vie += Integer.parseInt(strs[1]);
                        }

                        //把解决封装位"COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0"格式返回
                        String formatStr = String.format("COLLECTION:%d,COMMENT:%d,LIKES:%d,VIEWS:%d", col, com, lik, vie);
                        System.out.println("文章的id:"+key);
                        System.out.println("当前时间窗口内的消息处理结果："+formatStr);

                        return formatStr;
                    }
                },Materialized.as("hot-atricle-stream-count-001"))
                .toStream()
                .map((key, value) -> new KeyValue<>(key.key().toString(), formatObj(key.key().toString(), value.toString()))) // value的格式还需要修改
                .to(HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC);


        return stream;
    }

    /**
     *
     * @param artileId
     * @param value COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0
     * @return
     */
    private String formatObj(String artileId, String value) {
        ArticleVisitStreamMess mess = new ArticleVisitStreamMess();
        mess.setArticleId(Long.parseLong(artileId));

        String[] strs = value.split(",");// [COLLECTION:0,COMMENT:0]

        for (String str : strs) {
            String[] split = str.split(":"); // [COLLECTION,1]

            switch (UpdateArticleMess.UpdateArticleType.valueOf(split[0])){
                case COLLECTION:
                    mess.setCollect(Integer.parseInt(split[1]));
                    break;
                case COMMENT:
                    mess.setComment(Integer.parseInt(split[1]));
                    break;
                case LIKES:
                    mess.setLike(Integer.parseInt(split[1]));
                    break;
                case VIEWS:
                    mess.setView(Integer.parseInt(split[1]));
                    break;
            }
        }

        log.info("聚合消息处理之后的结果为:{}",JSON.toJSONString(mess));

        return JSON.toJSONString(mess);
    }
}
